package com.suning.sawp.service.custProtrait;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 生成密钥
 * 
 * @author 15050963
 *
 */
public class GenerateKeyPair {

    private static final Logger LOGGER = LoggerFactory.getLogger(GenerateKeyPair.class);

    private static final char[] bcdLookup = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
            'f' };

    // 店+APP用秘钥
    private String priKey;

    // MPDS用秘钥
    private String pubKey;

    public String getPriKey() {
        return priKey;
    }

    public void setPriKey(String priKey) {
        this.priKey = priKey;
    }

    public String getPubKey() {
        return pubKey;
    }

    public void setPubKey(String pubKey) {
        this.pubKey = pubKey;
    }

    public void run() {
        try {
            java.security.KeyPairGenerator keygen = java.security.KeyPairGenerator.getInstance("RSA");
            SecureRandom secrand = new SecureRandom();
            secrand.setSeed("mpds".getBytes()); // mpds为生成秘钥的字符串
            keygen.initialize(512, secrand); // 512为生成秘钥的精度
            KeyPair keys = keygen.genKeyPair();

            PublicKey pubkey = keys.getPublic();
            PrivateKey prikey = keys.getPrivate();

            pubKey = bytesToHexStr(pubkey.getEncoded());
            priKey = bytesToHexStr(prikey.getEncoded());

        } catch (java.lang.Exception e) {
            LOGGER.error("GenerateKeyPair 生成密钥对失败", e);
        }
    }

    /**
     * Transform the specified byte into a Hex String form.
     */
    public final String bytesToHexStr(byte[] bcd) {
        StringBuffer s = new StringBuffer(bcd.length * 2);

        for (int i = 0; i < bcd.length; i++) {
            s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);
            s.append(bcdLookup[bcd[i] & 0x0f]);
        }
        return s.toString();
    }

    /**
     * Transform the specified Hex String into a byte array.
     */
    public final byte[] hexStrToBytes(String s) {
        byte[] bytes;
        bytes = new byte[s.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        GenerateKeyPair n = new GenerateKeyPair();
        n.run();
    }
}
